using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;
//Written By: Jason Deatherage August 2008 Phoenix, AZ Home of the blazing inferno.
namespace SlideShowGenerator
{
    public partial class PhotoResizer : Form
    {
        public PhotoResizer()
        {
            InitializeComponent();
        }

        private void btnSourceDirectory_Click(object sender, EventArgs e)
        {
            DialogResult result = fbBrowserResize.ShowDialog();
            if (result == DialogResult.OK)
            {
                txtSourceDirectory.Text = fbBrowserResize.SelectedPath;
            }
        }//End btnSourceDirectory_Click

        private void PhotoResizer_Load(object sender, EventArgs e)
        {
            
        }//End of PhotoResizer_Load Function

        private void chkCreateThumbnails_CheckedChanged(object sender, EventArgs e)
        {
            if (chkCreateThumbnails.Checked == true)
            {
                lblThumbnailSize.Show();
                txtThumbnailSize.Show();
            }
            if (chkCreateThumbnails.Checked == false)
            {
                lblThumbnailSize.Hide();
                txtThumbnailSize.Hide();
            }
        }//End of chkCreatThumbnails_CheckedChanged

        private void btnResizePhotos_Click(object sender, EventArgs e)
        {
             int intFilesCreated = 0;
             

            if (txtSourceDirectory.Text == "")
            {
                MessageBox.Show("Please choose a source directory.");
            }
            else if (txtScaleSize.Text == "")
            {
                MessageBox.Show("Please enter a new width to resize to.");
            }
            else
            {
                
                string foldername = txtSourceDirectory.Text;
                int intNewWidth, intNewHeight, intNewWidthT, intNewHeightT;
                float flWidthCalc, flHeightCalc, flWidthCalcT, flHeightCalcT;
                string strFileExt;

                pbFilesResized.Visible = true;
                pbFilesResized.Value = 0;
                pbFilesResized.Maximum = Directory.GetFiles(foldername).Length;

                if (chkCreateThumbnails.Checked == true)
                {
                    if (Directory.Exists(txtSourceDirectory.Text + "\\thumbnails"))
                    {
                        //MessageBox.Show("True");
                    }
                    else
                    {
                        Directory.CreateDirectory(txtSourceDirectory.Text + "\\thumbnails");
                    }
                }//creates a thumbnail directory if needed

                //MessageBox.Show(Convert.ToString(Directory.GetFiles(foldername).Length));
                foreach (string f in Directory.GetFiles(foldername))
                {
                    pbFilesResized.Value++;
                    strFileExt = GetFileExtension(f);
                    if (strFileExt.ToUpper() == ".JPG" || strFileExt.ToUpper() == ".GIF" || strFileExt.ToUpper() == ".PNG" || strFileExt.ToUpper() == ".BMP" || strFileExt.ToUpper() == ".JPEG" || strFileExt.ToUpper() == ".TIFF" || strFileExt.ToUpper() == ".TIF")
                    {
                        
                        Image FullsizeImage;
                        Image NewScaledImage;
                        Image NewScaledImageT;
                        try
                        {

                            FullsizeImage = Image.FromFile(f);
                            
                            if (FullsizeImage.Width > FullsizeImage.Height)
                            {
                                intNewWidth = Convert.ToInt32(txtScaleSize.Text);
                                flWidthCalc = (float)intNewWidth / FullsizeImage.Width;
                                intNewHeight = Convert.ToInt32(FullsizeImage.Height * flWidthCalc);
                                //NewScaledImage = FullsizeImage.GetThumbnailImage(intNewWidth, intNewHeight, null, IntPtr.Zero);
                                NewScaledImage = new Bitmap(intNewWidth, intNewHeight, FullsizeImage.PixelFormat);
                                Graphics newGraphic = Graphics.FromImage(NewScaledImage);
                                newGraphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
                                newGraphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;
                                newGraphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                                Rectangle newRectangle = new Rectangle(0, 0, intNewWidth, intNewHeight);
                                newGraphic.DrawImage(FullsizeImage, newRectangle);
                                

                                //Gets a thumbnail at the default size of 150 px width
                                intNewWidthT = Convert.ToInt32(txtThumbnailSize.Text);
                                flWidthCalcT = (float)intNewWidthT / FullsizeImage.Width;
                                intNewHeightT = Convert.ToInt32(FullsizeImage.Height * flWidthCalcT);
                                NewScaledImageT = FullsizeImage.GetThumbnailImage(intNewWidthT, intNewHeightT, null, IntPtr.Zero);

                                EncoderParameter quality = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)80);
                                EncoderParameters encoderParams = new EncoderParameters(1);
                                encoderParams.Param[0] = quality;

                                ImageCodecInfo jpgCodec = GetEncoderInfo("image/jpeg");

                                if (chkCreateThumbnails.Checked == true)
                                {
                                    NewScaledImageT.Save(txtSourceDirectory.Text + "\\Thumbnails" + f.Substring(txtSourceDirectory.Text.Length, f.Length - txtSourceDirectory.Text.Length - strFileExt.Length) + "T" + strFileExt.ToLower(),jpgCodec,encoderParams);
                                    intFilesCreated++;
                                     
                                }

                              
                                FullsizeImage.Dispose();
                                File.Delete(f);
                                NewScaledImage.Save(f, jpgCodec,encoderParams);
                                intFilesCreated++;
                                
                            }
                            else
                            {
                                intNewHeight = Convert.ToInt32(txtScaleSize.Text);
                                flHeightCalc = (float)intNewHeight / FullsizeImage.Height;
                                intNewWidth = Convert.ToInt32(FullsizeImage.Width * flHeightCalc);
                                //NewScaledImage = FullsizeImage.GetThumbnailImage(intNewWidth, intNewHeight, null, IntPtr.Zero);
                                NewScaledImage = new Bitmap(intNewWidth, intNewHeight, FullsizeImage.PixelFormat);
                                Graphics newGraphic = Graphics.FromImage(NewScaledImage);
                                newGraphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
                                newGraphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;
                                newGraphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                                Rectangle newRectangle = new Rectangle(0, 0, intNewWidth, intNewHeight);
                                newGraphic.DrawImage(FullsizeImage, newRectangle);

                                intNewHeightT = Convert.ToInt32(txtThumbnailSize.Text);
                                flHeightCalcT = (float)intNewHeightT / FullsizeImage.Height;
                                intNewWidthT = Convert.ToInt32(FullsizeImage.Width * flHeightCalcT);
                                NewScaledImageT = FullsizeImage.GetThumbnailImage(intNewWidthT, intNewHeightT, null, IntPtr.Zero);

                                EncoderParameter quality = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)80);
                                EncoderParameters encoderParams = new EncoderParameters(1);
                                encoderParams.Param[0] = quality;

                                ImageCodecInfo jpgCodec = GetEncoderInfo("image/jpeg");

                                if (chkCreateThumbnails.Checked == true)
                                {

                                    NewScaledImageT.Save(txtSourceDirectory.Text + "\\Thumbnails" + f.Substring(txtSourceDirectory.Text.Length, f.Length - txtSourceDirectory.Text.Length - strFileExt.Length) + "T" + strFileExt.ToLower(),jpgCodec,encoderParams);
                                    intFilesCreated++;
                                    
                                }

                                FullsizeImage.Dispose();
                                File.Delete(f);
                                NewScaledImage.Save(f, jpgCodec, encoderParams);
                                intFilesCreated++;
                                
                            }



                            
                        }
                        catch (Exception Exc)
                        {
                            MessageBox.Show(Exc.Message.ToString());
                        }

                    }//End of If Statement
                    else
                    {
                        //MessageBox.Show("Wrong file format " + f.Substring(txtSourceDirectory.Text.Length + 1, f.Length - txtSourceDirectory.Text.Length - 1) + ".\n" + "Only accepts .JPG,.JPEG,.GIF,.PNG,.BMP,.TIFF,.TIF.");
                    }

                }//End of foreach
            }//End of top Else statement

            MessageBox.Show("Done." + "\n" + intFilesCreated + " images just resized.");
            pbFilesResized.Visible = false;
            
            Close();

        }//End of Resize Button Click

        private string GetFileExtension(string fileName)
        {
            if (fileName.Substring(fileName.Length - 4).ToUpper() == ".JPG")
            {
                return ".JPG";
            }
            else if (fileName.Substring(fileName.Length - 4).ToUpper() == ".GIF")
            {
                return ".GIF";
            }
            else if (fileName.Substring(fileName.Length - 4).ToUpper() == ".PNG")
            {
                return ".PNG";
            }
            else if (fileName.Substring(fileName.Length - 4).ToUpper() == ".BMP")
            {
                return ".BMP";
            }
            else if (fileName.Substring(fileName.Length - 5).ToUpper() == ".JPEG")
            {
                return ".JPEG";
            }
            else if (fileName.Substring(fileName.Length - 5).ToUpper() == ".TIFF")
            {
                return ".TIFF";
            }
            else if (fileName.Substring(fileName.Length - 4).ToUpper() == ".TIF")
            {
                return ".TIF";
            }
            else
            {
                return "";
            }
        }// End of GetFileExtension

        private ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            // Get image codecs for all image formats 
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

            // Find the correct image codec 
            for (int i = 0; i < codecs.Length; i++)
            {
                if (codecs[i].MimeType == mimeType)
                    return codecs[i];
            }
            return null;
        } //Gets Image Codec for compression

       
     }


    
}